package com.ma5d.driver.driver.service.impl;

import com.ma5d.driver.common.exception.DriverException;
import com.ma5d.driver.common.result.ResultCodeEnum;
import com.ma5d.driver.driver.service.CiService;
import com.ma5d.driver.driver.service.CosService;
import com.ma5d.driver.model.vo.driver.CosUploadVo;
import com.ma5d.driver.driver.properties.TencentProperties;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.UUID;

@Service
public class CosServiceImpl implements CosService {

    @Resource
    private TencentProperties properties;

    @Resource
    private CiService ciService;

    @Override
    public CosUploadVo upload(MultipartFile file, String path) {
        // 获取 cosClient 对象
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.getSize());
        metadata.setContentEncoding("utf-8");
        metadata.setContentType(file.getContentType());
        String uploadPath = "/driver/" + path + "/" + UUID.randomUUID().toString().replaceAll("-", "");
        COSClient cosClient = this.getCOSClient();

        PutObjectRequest putObjectRequest;
        try{
            putObjectRequest = new PutObjectRequest(properties.getBucketPrivate(),
                    uploadPath, file.getInputStream(), metadata);
        } catch (IOException e) {
            e.printStackTrace();
            throw new DriverException(ResultCodeEnum.FAIL);
        }
        putObjectRequest.setStorageClass(StorageClass.Standard);
        cosClient.putObject(putObjectRequest);
        cosClient.shutdown();

        // 图片审核
        // Boolean imageAuditing = ciService.imageAuditing(uploadPath);
        // if(!imageAuditing){
        //     cosClient.deleteObject(properties.getBucketPrivate(), uploadPath);
        //     throw new DriverException(ResultCodeEnum.IMAGE_AUDITION_FAIL);
        // }
        
        // 返回 vo 对象
        CosUploadVo cosUploadVo = new CosUploadVo();
        cosUploadVo.setUrl(uploadPath);
        String imageUrl = this.getImageUrl(uploadPath);
        cosUploadVo.setShowUrl(imageUrl);
        return cosUploadVo;
    }

    private String getImageUrl(String uploadPath) {
        if(!StringUtils.hasText(uploadPath)){
            return "";
        }
        COSClient cosClient = this.getCOSClient();
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(properties.getBucketPrivate(), uploadPath, HttpMethodName.GET);
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(15);
        request.setExpiration(Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()));
        URL url = cosClient.generatePresignedUrl(request);
        cosClient.shutdown();
        return url.toString();
    }

    public COSClient getCOSClient() {
        String secretId = properties.getSecretId();
        String secretKey = properties.getSecretKey();
        BasicCOSCredentials credentials = new BasicCOSCredentials(secretId, secretKey);
        Region region = new Region(properties.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient = new COSClient(credentials, clientConfig);
        return cosClient;
    }
}
